<?php


namespace app\cms\admin\controller\config;

use app\cms\community\lib\utils\themeUtil;
use app\cms\model\themeModel;
use app\cms\tags\config;
use iflow\auth\Authorize\AuthAnnotation;
use iflow\exception\Adapter\HttpResponseException;
use iflow\fileSystem\lib\FileList;
use iflow\Response;
use iflow\Router\Controller;
use iflow\Router\implement\Request\{PostMapping, DeleteMapping, GetMapping};

#[Controller('%cmsAdmin%/theme')]
class theme
{

    /**
     * 上传站点主题
     * @return Response
     */
    #[PostMapping]
    #[AuthAnnotation('theme', 'themeReadWrite|themeWrite')]
    public function uploadTheme(): Response
    {
        try {
            // 解压文件 移至协程处理
            go(function () {
                $themeUtil = app(themeUtil::class);
                throw new HttpResponseException(
                    $themeUtil -> setFiles(
                        request() -> file('file')
                    ) -> saveTheme()
                );
            });
            return message() -> success('上传成功');
        } catch (\Exception $exception) {
            if ($exception instanceof HttpResponseException) {
                return $exception -> getResponse();
            }
            return message()->update_failed($exception -> getMessage());
        }
    }

    /**
     * 删除主题
     * @param int $site_theme_id
     * @return Response
     */
    #[DeleteMapping('delete_theme/<[0-9]{1,}:site_theme_id>')]
    #[AuthAnnotation('theme', 'themeReadWrite|themeWrite')]
    public function deleteTheme(int $site_theme_id): Response
    {
        // 删除站点信息
        $them = new themeModel();
        $info = $them -> getThemeFind($site_theme_id);
        if (!$info) return message() -> nodata('暂无主题信息');

        $staticPath = app() -> getRunTimePath(). 'store/temp/'.$info['site_theme_uuid'];
        is_file($staticPath) && unlink($staticPath);

        $viewPath = config('template@view_root_path'). 'theme' . DIRECTORY_SEPARATOR . $info['site_theme_uuid'];
        if (is_dir($viewPath)) {
            (new FileList()) -> removeDir(
                config('template@view_root_path'). 'theme' . DIRECTORY_SEPARATOR . $info['site_theme_uuid']
            );
        }

        return $them -> deleteData([
            'site_theme_id' => $site_theme_id
        ]);
    }

    /**
     * 获取主题列表
     * @param int $status
     * @param string $author
     * @param string $name
     * @param string $license
     * @return Response
     */
    #[GetMapping]
    #[AuthAnnotation('theme', 'themeReadWrite|themeRead')]
    public function getThemeList(
        int $status = -1,
        string $author = '',
        string $name = '',
        string $license = ''
    ): Response {
        return (new themeModel()) -> getThemeList(
            $status, $author, $name, $license
        );
    }

    /**
     * 主题绑定域名
     * @param string $domain
     * @param int $site_theme_id
     * @return Response
     */
    #[PostMapping]
    #[AuthAnnotation('theme', 'themeReadWrite|themeWrite')]
    public function bindThemeDomain(string $domain, int $site_theme_id): Response
    {
        return (new themeModel()) -> setThemeDomain($domain, $site_theme_id);
    }

    /**
     * 预览模板
     * @param string $template_id
     * @param string $path
     * @return Response
     */
    #[GetMapping('review/<[?:template_id]>')]
    #[AuthAnnotation('theme', 'themeReadWrite|themeWrite')]
    public function review(string $template_id, string $path = 'index'): Response
    {
        $theme = (new themeModel()) -> getThemeFind($template_id);
        if ($theme) return message() -> nodata('模板不存在');

        $template = config('template');

        $path = $template['view_root_path'].trim($path, '/'). ".${template['view_suffix']}";

        if (!file_exists($path)) {
            return message() -> nodata('模板文件不存在');
        }

        // 获取站点配置
        $config = (new config()) -> getConfig();

        return view("theme/{$theme['site_theme_uuid']}/html/${path}", array_merge([
            'config' => $config
        ], request() -> params()));
    }

    /**
     * 获取主题文件列表
     * @param string $template_id
     * @return Response
     */
    #[GetMapping]
    #[AuthAnnotation('theme', 'themeReadWrite|themeRead')]
    public function getThemeFileList(string $template_id): Response
    {
        // TODO: 获取指定主题代码文件列表
        $theme = (new themeModel()) -> getThemeFind($template_id);
        if (!$theme) return message() -> nodata('暂未查询到该主题信息');

        $fileList = [];

        $viewRoot = config('template@view_root_path'). 'theme' . DIRECTORY_SEPARATOR . $theme['site_theme_uuid']  .DIRECTORY_SEPARATOR;

        $themeConfig = json_decode(file_get_contents($viewRoot . 'theme.json'), true);

        $staticRoot = app() -> getRootPath() . 'public'. DIRECTORY_SEPARATOR . 'static'
            . DIRECTORY_SEPARATOR . ($themeConfig['staticPath'] ?? $theme['site_theme_uuid']) .DIRECTORY_SEPARATOR;

        $fileUtils = new FileList();

        $fileList['static'] = $fileUtils -> loadFileList($staticRoot, traverse: true);
        $fileList['view'] = $fileUtils -> loadFileList($viewRoot, traverse: true);

        return message() -> success('查询数据成功', [
            'fileList' => $fileList
        ]);
    }

    /**
     * 获取主题文件内容
     * @param int $template_id
     * @param string $filePath
     * @return Response
     */
    #[GetMapping]
    #[AuthAnnotation('theme', 'themeReadWrite|themeRead')]
    public function getThemeFileContent(int $template_id, string $filePath): Response
    {
        // TODO: 获取指定主题下文件内容
        $theme = (new themeModel()) -> getThemeFind($template_id);
        if (!$theme) return message() -> nodata('暂未查询到该主题信息');

        if (!file_exists($filePath)) return message() -> nodata('当前主题下 该文件不存在');

        $finfo = finfo_open(FILEINFO_MIME);
        $mime = finfo_file($finfo, $filePath);
        finfo_close($finfo);

        return message() -> success('获取文件内容成功', [
            'content' => file_get_contents($filePath),
            'ext' => pathinfo($filePath, PATHINFO_EXTENSION),
            'mime' => $mime
        ]);
    }


    /**
     * 更新主题文件代码
     * @param string $filePath
     * @param string $content
     * @return Response
     */
    #[PostMapping]
    #[AuthAnnotation('theme', 'themeReadWrite')]
    public function changeThemeFileContent(string $filePath, string $content): Response
    {
        // TODO: 修改指定主题文件 代码
        $length = file_put_contents($filePath, $content);
        return message() -> success('保存成功', [
            'saveLength' => $length
        ]);
    }

    /**
     * 删除文件
     * @param string $template_id
     * @param string $filePath
     * @return Response
     */
    #[DeleteMapping]
    #[AuthAnnotation('theme', 'themeReadWrite')]
    public function deleteThemeFile(string $template_id, string $filePath): Response
    {
        // TODO: 删除指定主题 文件
        $theme = (new themeModel()) -> getThemeFind($template_id);
        if (!$theme) return message() -> nodata('暂未查询到该主题信息');
        file_exists($filePath) && unlink($filePath);
        return message() -> success('删除文件成功');
    }
}
